package com.uujava.minibox.ui.panel;

import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * @功能：设置JPanel的背景图片
 * @author k
 * @address 《梦续残缘》工作室
 * @version 1.0
 * @日期：2012-08-11 15:08:05
 * @see com.mxcyk.minibox.skins.ImagePane;
 */
public class ImagePane extends JPanel {

	public ImagePane() {}
	// =================================================================================================
	private Image backImage = null;// 背景图片

	// 传入图片路径设置背景
	public void setBackImage(File file) {
		try {
			backImage = ImageIO.read(file);
		} catch (IOException ex) {
			backImage = null;// 如果获得图片路径为空则image=null
		}
	}

	// 传入图片路径设置背景
	public void setBackImage(String bg) {
		try {
			backImage = new ImageIcon(getClass().getResource(bg)).getImage();
		} catch (Exception e) {
			System.out.println("ImagePane类设置背景出错");
			backImage = null;// 如果获得图片路径为空则image=null
		}
	}

	// 传入图片设置背景
	public void setBackImage(Image image) {
		this.backImage = image;
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		Image im = new ImageIcon("").getImage();
		if ((backImage != null) && (!backImage.equals(im)))// 图标不为空且图片不为空
			g.drawImage(backImage, 0, 0, this.getWidth(), this.getHeight(),
					null);
	}

	// ======================================================================================================
	public static void main(String[] args) {
		JFrame frame = new JFrame();
		ImagePane imp = new ImagePane();
		frame.getContentPane().add(imp);
		imp.setBackImage(new File("image/1.jpg"));

		frame.setSize(800, 600);
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	}
}